package com.qdairlines.shiro.realm;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.config.Ini;
import org.apache.shiro.config.Ini.Section;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.qdairlines.entity.user.Permission;
import com.qdairlines.service.user.PermissionService;
import com.qdairlines.service.user.RoleService;


public class ChainDefinitionSectionMetaSource implements FactoryBean<Ini.Section>{

	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleService roleService;
	
	
	private String filterChainDefinitions;
	
	/** 
     * 动态premission 
     */  
    public static final String PREMISSION_STRING="roleOrFilter[\"{0}\"]";  
	
	@Override
	public Section getObject() throws Exception {

        List<Permission> list = permissionService.listData(new Permission());  
  
        Ini ini = new Ini();  
        //加载默认的ur
        ini.load(filterChainDefinitions);  
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);  
        //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,  
        //里面的键就是链接URL,值就是存在什么条件才能访问该链接  
        for (Iterator<Permission> it = list.iterator(); it.hasNext();) {  
  
        	Permission permission = it.next();
        	String roleNames=roleService.getRoleNamesByPermissionCode(permission.getPermissionCode());
        	//如果不为空值添加到section中
            if(StringUtils.isNotEmpty(permission.getUrl()) && StringUtils.isNotEmpty(roleNames)) {  
                section.put(permission.getUrl(),  MessageFormat.format(PREMISSION_STRING,roleNames));  
            }  
  
        }  
  
        return section;  
	}

	 /** 
     * 通过filterChainDefinitions对默认的url过滤定义 
     *  
     * @param filterChainDefinitions 默认的url过滤定义 
     */  
    public void setFilterChainDefinitions(String filterChainDefinitions) {  
        this.filterChainDefinitions = filterChainDefinitions;  
    }  
  
    public Class<?> getObjectType() {  
        return this.getClass();  
    }  
  
    public boolean isSingleton() {  
        return false;  
    }  

}
